<template>
  <page-meta :root-font-size="globalData.fontsize + 'px'" user-scalable="no" viewport-fit="cover" style="display: block"></page-meta>
  <view>
    <view :style="globalData.appStyle.customizeBarStyle">
      <uni-nav-bar :height="globalData.navBarInfo.height" title="采购发布" color="#fff" fixed backgroundColor="#FF7C00">
        <block slot="left">
          <uni-icons color="white" class="icon-left" @click="navigateBackPage" type="left" size="23"></uni-icons>
          <uni-icons color="white" @click="switchTabPage(`/pages/procurementPage`)" type="home" size="23"></uni-icons>
        </block>
      </uni-nav-bar>
    </view>

    <view :style="globalData.appStyle.customizeContentStyle">
      <scroll-view class="common_form" :style="formContentStyle" scroll-y>
        <uni-forms ref="form" class="h100p" :modelValue="formData">
          <uni-forms-item label="采购类别" label-width="100px" name="purchaseCategory">
            <view class="flr fla flb" @click.stop="jumpToPageWithEvent(`/pages/global/categorySelection/index?searchMode=2&newSource=${formData.purchaseCategory ? 1 : 0}`)">
              <input type="text" v-model="formData.purchaseCategory" class="input" placeholder="请选择采购类别" />
              <uni-icons type="right" size="20"></uni-icons>
            </view>
          </uni-forms-item>
          <view class="content_line"> </view>
          <!-- 采购类型 非跳转-->
          <CompletePayInfo v-if="showCompletePart" ref="CompletePayInfo" :targetType="0" @setCompleteInfo="setCompleteInfo" :params="{ settlementMethod: formData.settlementMethod, demandQty: formData.demandQty, supplyQualification: formData.supplyQualification, contactLimit: formData.contactLimit, picsUrl: formData.picsUrl, fileUrl: formData.fileUrl, fileName: formData.fileName }" />
          <view v-if="pushType == 2" class="history-selected">
            <view class="top-title">历史选择类别</view>
            <view class="flw">
              <view class="selected-box" v-for="(category, key) in historySelectedCategory" :key="key" @click="selectedCurrent(category)">
                {{ category.categoryName }}
              </view>
            </view>
          </view>
          <view class="content_line"> </view>
          <uni-forms-item label=" 交货地址" label-width="100px" name="deliveryAddress">
            <view class="flr fla flb">
              <input type="text" class="input" v-model="formData.deliveryAddress" placeholder="请输入交货地址" maxlength="15" @change="setDetailDesc" @input="setValue()" />
              <text>{{ deliveryAddressLength }}/15</text>
            </view>
          </uni-forms-item>
          <view class="content_line"></view>
          <uni-forms-item label="标题(选题)" label-width="100px" name="title">
            <view class="flr fla flb">
              <input type="text" class="input" v-model="formData.title" placeholder="请输入标题" maxlength="15" @input="setValue()" />
              <text>{{ titleLength }}/15</text>
            </view>
          </uni-forms-item>
          <view class="content_line"></view>
          <view class="need_style">
            <view class="flr fla flb">
              <text class="common_form_label_style">需求详情</text>
              <text class="need_desc_label">点击下方输入框可以修改详情</text>
            </view>
            <view class="need_desc">
              <textarea v-model="formData.detailInfo" maxlength="150" placeholder-style="color: rgba(255, 180, 110, 1);font-size:16rem;" @input="setValue()"></textarea>
              <text>{{ detailInfoLength }}/150</text>
            </view>
          </view>
          <view class="content_line"></view>
          <view class="phone_content">
            <uni-forms-item label="手机号" label-width="100px" name="contactPhoneNumber">
              <view class="flr fla flb">
                <input type="text" v-model="formData.contactPhoneNumber" class="input" placeholder="请输入手机号" maxlength="11" />
                <SMSCountdown v-if="showSMSPart" :phoneNumber="formData.contactPhoneNumber" :totalSeconds="60" @resend="onResend"></SMSCountdown>
              </view>
            </uni-forms-item>
            <view v-if="showSMSPart" class="warning_desc">
              <uni-icons type="info" size="29"></uni-icons>
              更换为非授权手机号时，需要填写验证码和联系人，否则发布失败</view
            >
          </view>
          <view v-if="showSMSPart" class="content_line"></view>
          <uni-forms-item v-if="showSMSPart" label="验证码" label-width="100px" name="verificationCode">
            <view class="flr fla flb">
              <input type="text" v-model="formData.verificationCode" class="input" placeholder="请输入验证码" />
            </view>
          </uni-forms-item>
          <view class="content_line"></view>
          <view v-if="pushType == 2 && lastHistoryInfo.id" class="need_style">
            <view class="flr fla flb">
              <text class="common_form_label_style">历史版本</text>
              <view class="need_desc_label flca" @click="jumpToPage('/pages/procurement/myProcurement')">
                <text class="need_control">管理需求</text>
                <uni-icons type="right" size="20" color="#FF7C00"></uni-icons>
              </view>
            </view>
            <view class="history_need_content">
              <view class="flb">
                <view class="flr">
                  <view class="common_status" v-if="lastHistoryInfo.status === '1'">审核中</view>
                  <view class="common_status status_zzz" v-if="lastHistoryInfo.status === '2'">正在找</view>
                  <view class="common_status" v-if="lastHistoryInfo.status === '3'">未通过</view>
                  <view class="common_status" v-if="lastHistoryInfo.status === '4'">已下架</view>
                  <text :class="{ common_title: true, 'line-clamp-1': true, w220: true }">{{ lastHistoryInfo.title }}</text>
                </view>
                <view class="common_status status_fz" @click="copyInfoToEdit()">复制</view>
              </view>
              <view class="content_desc line-clamp-2"> {{ lastHistoryInfo.detailInfo }}</view>
              <view class="content_bottom flca flb">
                <view class="flc fs14" style="color: #a6a6a6">
                  <text>{{ lastHistoryInfo.createTime }}</text>
                  <text>
                    <text class="fw7">{{ lastHistoryInfo.contact }}</text>
                    {{ lastHistoryInfo.contactPhoneNumber }}
                  </text>
                </view>
                <view class="flr">
                  <view v-if="['1', '2', '3'].indexOf(lastHistoryInfo.status) !== -1" class="common_status status_xj mr10" @click.stop="offShelf(lastHistoryInfo)">下架</view>
                  <view v-if="['1', '2', '3', '4'].indexOf(lastHistoryInfo.status) !== -1" class="common_status status_xg mr10" @click.stop="jumpProcurement('modify')">修改</view>
                  <view v-if="lastHistoryInfo.status === '4'" class="common_status status_cxfb" @click.stop="jumpProcurement('republish')">重新发布</view>
                </view>
              </view>
            </view>
          </view>
          <uni-forms-item v-if="userInfo.phoneNumber !== formData.contactPhoneNumber" label="联系人" label-width="100px" name="contact">
            <view class="flr fla flb">
              <input type="text" v-model="formData.contact" class="input" placeholder="请输入联系人" />
            </view>
          </uni-forms-item>
          <view class="content_line"></view>
          <UploadFile uploadFileType="img" title="图片" :picsUrl="formData.picsUrl" :limit="3" @setFileInfo="setFileInfo" />
          <view class="content_line"></view>
          <UploadFile uploadFileType="file" title="文件" :fileUrl="formData.fileUrl" :fileName="formData.fileName" @setFileInfo="setFileInfo" />
          <view v-if="showCompleteCompanyBtn" class="add_bottom_label" @click="jumpToPage('/pages/my/enhanceInfo')">
            <text class="first_label">完善信息获得更多收益，点击</text>
            <text class="last_label">去完善</text>
          </view>
        </uni-forms>
      </scroll-view>
      <CommitBtn btnText="立即发布" @CommitEvent="CommitEvents"></CommitBtn>
    </view>
  </view>
</template>

<script>
const api = require('@/utils/request.js');
import SMSCountdown from '@/component/SMSCountdown.vue';
import UploadFile from '@/component/UploadFile.vue';
import commonMxins from '@/mixins/common.js';
import CommitBtn from '@/component/CommitBtn.vue';
import CompletePayInfo from '@/component/CompletePayInfo.vue';
export default {
  mixins: [commonMxins],
  components: {
    UploadFile,
    SMSCountdown,
    CommitBtn,
    CompletePayInfo
  },
  data() {
    return {
      pushType: 1, // 1- 正常发布 2-快捷发布
      lastHistoryInfo: {}, // 最后一条历史销售数据
      historySelectedCategory: [], // 选择类别
      detailInfoLength: 0,
      titleLength: 0,
      deliveryAddressLength: 0,
      userInfo: {
        phoneNumber: '',
        isPartner: '2'
      },
      regex: /^1[3-9]\d{9}$/,
      navLeftStyle: '',
      formData: {
        verificationCode: '',
        categoryName: '', // 大类名称
        purchaseCategory: '', // 大类或小类
        deliveryAddress: '',
        title: '',
        contactPhoneNumber: '',
        detailInfo: '',
        file: {},
        contact: '',
        fileUrl: '',
        fileName: '',
        picsUrl: '',
        settlementMethod: '',
        demandQty: '',
        supplyQualification: '',
        contactLimit: ''
      },
      url: '',
      rules: {},
      currentType: 'add',
      formContentStyle: '',
      showCompleteCompanyBtn: true,
      commitUrlInfo: {
        add: '/purchaseInfo/publish',
        republish: '/purchaseInfo/rePublish',
        modify: '/purchaseInfo/modify'
      }
    };
  },
  onLoad(options) {
    this.pushType = options.pushType == 2 ? 2 : 1;
    options.pushType == 2 && this.queryHistoryInfo();
    this.getAllCategory();
    this.initData(options);
    const bottomHeight = 55 * this.globalData.pageHeightProportion;
    this.formContentStyle = `height: ${this.globalData.customizeInfo.customizeContentHeight - bottomHeight}rem`;
  },
  onShow() {
    this.getHistoryCategoryByLocal();
  },
  computed: {
    showSMSPart() {
      let booleanInfo = false;
      booleanInfo = this.userInfo.phoneNumber !== this.formData.contactPhoneNumber && this.userInfo.isPartner != 1;
      return booleanInfo;
    },
    showCompletePart() {
      let booleanInfo = false;
      // 复制、重新发布、修改
      booleanInfo = !this.formData.id || ['republish', 'modify'].indexOf(this.currentType !== -1) || !this.formData.settlementMethod || !this.formData.demandQty || !this.formData.supplyQualification || !this.formData.contactLimit;
      return booleanInfo;
    }
  },
  methods: {
    onShareAppMessage(res) {
      return { title: 'E商机-商机触手可得', path: `/pages/procurementPage?shareId=${this.globalData.userInfo.id}` };
    },
    onShareTimeline(res) {
      return { title: 'E商机-商机触手可得', path: '/pages/procurementPage' };
    },
    // 判断下面的去完善公司信息是否需要展示
    async getEnhanceInfo() {
      let res = await api.request({ url: '/appUser/queryEnterpriseInfo', method: 'GET' });
      if (res.data) {
        this.showCompleteCompanyBtn = !!res.data.auditStatus === '1';
      }
    },
    setFileInfo(value) {
      if (typeof value === 'object') {
        this.formData.fileUrl = value.url;
        this.formData.fileName = value.fileName;
      } else {
        this.formData.picsUrl = value;
      }
    },
    //  历史需求进行复制等操作
    // 复制
    copyInfoToEdit() {
      const { purchaseCategory, categoryName, deliveryAddress, title, contactPhoneNumber, detailInfo, file, contact, fileUrl, fileName, picsUrl, settlementMethod, demandQty, supplyQualification, contactLimit } = this.lastHistoryInfo;
      this.formData = { purchaseCategory, categoryName, deliveryAddress, title, contactPhoneNumber, detailInfo, file, contact, fileUrl, fileName, picsUrl, settlementMethod, demandQty, supplyQualification, contactLimit };
      this.setValue();
      this.$forceUpdate();
      this.formData.detailInfo = detailInfo;
    },
    //跳转详情页，type modify表示修改republish表示重新发布
    jumpProcurement(status) {
      this.currentType = status;
      this.formData = { ...this.lastHistoryInfo };
    },
    // 下架数据
    async offShelf(item) {
      let res = await api.request({ url: '/purchaseInfo/offShelf', data: { purchaseInfoId: item.id }, method: 'GET' });
      if (res.code === 200) {
        uni.showToast({ title: '下架成功', icon: 'success', duration: 2000 });
        this.queryHistoryInfo();
      }
    },
    // 获取历史采购信息
    async queryHistoryInfo() {
      const res = await api.request({ url: '/purchaseInfo/queryLatestOne', data: {}, method: 'GET' });
      this.lastHistoryInfo = res.data || {};
    },
    // 获取历史选择类别
    getHistoryCategoryByLocal() {
      const historyList = uni.getStorageSync('historySelectedCategory');
      this.historySelectedCategory = historyList ? JSON.parse(historyList) : [];
    },
    // 选择历史类型
    selectedCurrent(obj) {
      this.formData.purchaseCategory = obj.categoryName;
      this.formData.categoryName = obj.parentName;
      this.setDetailDesc();
    },
    // 回退
    navigateBackPage() {
      uni.navigateBack({ delta: 1 });
    },
    switchTabPage(url) {
      uni.switchTab({ url });
    },
    /**
     * 初始化，判断当前页面跳转过来是新增还是编辑还是重新发布
     *  add-新增 modify-修改 republish-重新发布
     */
    async initData({ type, purchaseInfoId }) {
      this.currentType = type ? type : this.currentType;
      if (type && type !== 'add') {
        await this.queryInfoDetail(purchaseInfoId);
      } else {
        this.queryCurrentUserAddress();
      }
      this.getEnhanceInfo();
      this.getCurrentUserInfo();
    },
    // 查询当前发布人所在省市
    queryCurrentUserAddress() {
      api.request({ url: '/address/getAddress', data: {}, method: 'GET' }).then(async res => {
        const result = await api.request({ url: `https://qifu.baidu.com/ip/geo/v1/district?ip=${res.data.clientIp}`, fullUrl: true, method: 'GET' });
        const { city } = result.data;
        this.formData.deliveryAddress = `${city ? city : ''}`;
        this.setValue();
        this.setDetailDesc();
      });
    },

    async queryInfoDetail(purchaseInfoId) {
      const res = await api.request({ url: '/purchaseInfo/getInfo', data: { purchaseInfoId }, method: 'GET' });
      this.formData = { ...res.data };
      this.setValue();
    },
    // 重新发送短信
    onResend(code) {
      console.log('短信发送成功');
    },
    // 获取当前登录人信息
    async getCurrentUserInfo() {
      this.userInfo = this.globalData.userInfo;
      this.formData.contact = this.globalData.userInfo.nickName || '';
      this.formData.contactPhoneNumber = this.globalData.userInfo.phoneNumber || '';
    },
    async getAllCategory() {
      let res = await api.request({ url: '/category/queryAll', data: {}, method: 'GET' });
      this.categoryList = res.data;
    },
    async CommitEvents() {
      const url = this.commitUrlInfo[this.currentType];
      if (!this.regex.test(this.formData.contactPhoneNumber)) {
        uni.showToast({ title: '请输入正确的手机号信息', icon: 'none' });
        return;
      }
      if (this.formData.purchaseCategory === '' || this.formData.deliveryAddress === '') {
        uni.showToast({ title: '请完善采购信息', icon: 'none' });
        return;
      }
      // 当前手机未发生变更
      // 当前手机号发生变更，且用户为合伙人
      // 当前手机号发生变更，且用户不是合伙人
      if ((this.userInfo.phoneNumber !== this.formData.contactPhoneNumber && this.userInfo.isPartner != 1 && this.formData.verificationCode) || (this.userInfo.phoneNumber !== this.formData.contactPhoneNumber && this.userInfo.isPartner == 1) || this.userInfo.phoneNumber === this.formData.contactPhoneNumber) {
        this.$refs.CompletePayInfo.confirmPopup();
        let res = await api.request({ url, data: { ...this.formData }, method: 'POST' });
        if (res.code === 200) {
          uni.navigateTo({ url: `/pages/procurement/myProcurement` });
          this.formData = {
            verificationCode: '',
            purchaseCategory: '',
            deliveryAddress: '',
            title: '',
            contactPhoneNumber: '',
            detailInfo: '',
            file: {},
            contact: '',
            fileUrl: '',
            fileName: '',
            picsUrl: ''
          };
        } else {
          uni.showToast({ title: res.msg, icon: 'none', duration: 1500 });
        }
      }
    },
    jumpToPage(url) {
      uni.navigateTo({ url });
    },
    jumpToPageWithEvent(url) {
      uni.navigateTo({
        url,
        events: {
          getCategoryInfo: info => {
            this.getCategoryValue(info);
          }
        }
      });
    },
    getCategoryValue(info) {
      const { parentName, categoryName } = info;
      this.formData.categoryName = parentName;
      this.formData.purchaseCategory = categoryName;
      this.setDetailDesc();
    },
    // 类别、地址发生变更后，数据显示在详情部分
    setDetailDesc() {
      this.formData.detailInfo = this.formData.deliveryAddress + '求购' + this.formData.purchaseCategory;
    },
    setValue() {
      this.deliveryAddressLength = this.formData.deliveryAddress.length;
      this.titleLength = this.formData.title.length;
      this.detailInfoLength = this.formData.detailInfo.length;
    },
    // 配置完善信息字段
    setCompleteInfo(info) {
      if (Object.keys(info).length > 0) {
        const { settlementMethod, demandQty, supplyQualification, contactLimit, fileUrl, picsUrl, fileName } = info;
        this.formData = { ...this.formData, settlementMethod, demandQty, supplyQualification, contactLimit, fileUrl, picsUrl, fileName };
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
